package cn.bugstack.domain.strategy.service.rule.chain.factory;

import cn.bugstack.domain.strategy.model.entity.StrategyEntity;
import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.rule.chain.ILogicChain;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Title: DefaultChainFactory
 * @Author lz
 * @Date 2025/8/2 20:53
 * @description: 工厂(构造责任链)
 */
@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainMapGroup;
    protected final IStrategyRepository repository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainMapGroup, IStrategyRepository repository) {//依赖注入的方式，初始化的结构不会为空
        this.logicChainMapGroup = logicChainMapGroup;
        this.repository = repository;
    }
    /**
     * 通过策略ID构造抽奖规则链
     * */
    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
        // 如果未配置策略规则，则只装填一个默认责任链
        String[] ruleModels = strategy.ruleModels();
        if (null == ruleModels || ruleModels.length == 0) return logicChainMapGroup.get("rule_default");
        // 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight 此数据从Redis缓存中获取（具体顺序都是在数据库中配置好的）
        ILogicChain logicChain=logicChainMapGroup.get(ruleModels[0]);
        ILogicChain current=logicChain;
        for (int i = 1; i < ruleModels.length; i++){//按照顺序添加责任链节点
            ILogicChain nextChain= logicChainMapGroup.get(ruleModels[i]);//都是根据配置的key从map中获取
            current=current.appendNext(nextChain);
        }
        current.appendNext(logicChainMapGroup.get("rule_default"));
        return logicChain;

    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO{
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }

}
